
import RsaUtils from './RsaUtils';
import publicKey from '../config/rsa';
import { createHash } from 'crypto';
import { exec } from 'child_process';
import encoding from 'encoding-japanese';
import iconv from 'iconv-lite';
import { shell } from 'electron';
import { ipcRenderer } from 'electron';
import undici, { Dispatcher } from 'undici';
import { v4 as uuidv4 } from 'uuid';
import fs from 'fs';


const readFileSync = (path: string) => {
    const buffer = fs.readFileSync(path);
    let code = encoding.detect(buffer) as string;
    if (code.toLocaleLowerCase() != 'utf8') {
        code = 'gbk';
    }
    const text = iconv.decode(Buffer.from(buffer), code);
    return text;
}


const sign = (str: string) => {
    return createHash('sha1').update(str).digest('hex');
}



/**
 * 公钥解密
 * @param text 
 * @returns 
 */
const rsaDecrypt = (text: string) => {
    return RsaUtils.decryptWithWithPublicKey(publicKey, text);
}

/**
 * 公钥加密
 * @param text 
 * @returns 
 */
const rsaEncrypt = (text: string) => {
    return RsaUtils.encryptWithPublicKey(publicKey, text);

}

/**
 * 102ed44a1ce5910cb9268bd8740ab627
 * 发送评论
 * @param opts.msg   发言内容
 * @param opts.topic 主播 51bb52ca-12ca-4989-ab5b-3339a15a3310
 * @param opts.sid  发言者 102ed44a1ce5910cb9268bd8740ab627
 * @returns 
 */
const publish = async (opts: { msg: string, topic: string, sid: string }): Promise<any | null> => {

    const params = `{"content":"${opts.msg}","renders":"{}","topic":"${opts.topic}"}`;
    const headers: any = {
        'Host': 'guide-acs.m.taobao.com',
        'x-app-conf-v': '0',
        'x-bx-version': '6.5.80',
        'x-pv': '6.3',
        'User-Agent': 'MTOPSDK%2F1.9.3.48%20%28iOS%3B14.4%3BApple%3BiPhone12%2C5%29',
        'x-page-name': 'TBHomeViewController',
        'x-sign': 'izDdOU002xAAKGUzbXLbePZb3%2FxjCHU4bLKqTnneBZuMZbGO9VzWm4Jl5mhlMcu16lD1OG8hyk5ugkF8xnkpjIQ8h5k1SGU4ZUhlOG',
        'x-appkey': '23086819',
        'x-sid': opts.sid,
        'x-t': Math.floor(Date.now() / 1000)
    }
    try {

        const res = await undici.request("https://guide-acs.m.taobao.com/", {
            method: "GET",
            path: "gw/mtop.taobao.iliad.comment.publish/1.0",
            query: {
                data: params
            },
            headers: headers
        } as Dispatcher.DispatchOptions);
        const body: any = await res.body.json();
        return body;
    } catch (e) {
        return null;
    }

}


let __DEVICEID__ = '';
const _getDeviceId = () => {
    return new Promise<string>((res) => {
        if (__DEVICEID__) {
            return res(__DEVICEID__);
        }
        exec('wmic cpu get processorid', (_err, out, _der) => {
            if (out) {
                try {
                    const str = out.toString().split('\n').slice(1, -1).join('');
                    __DEVICEID__ = createHash('sha1').update(str + '888').digest('hex');
                } catch (error) {

                }
            }
            res(__DEVICEID__);
        });
    });
}

const getDeviceId = async () => {
    __DEVICEID__ = await _getDeviceId();
    if (!__DEVICEID__) {
        __DEVICEID__ = cache.get("__DEVICEID__");
        if (__DEVICEID__) {
            __DEVICEID__ = createHash('sha1').update(uuidv4()).digest('hex');
            cache.set("__DEVICEID__", __DEVICEID__);
        }
    }
    return __DEVICEID__;
}


const getAppVersion = () => {
    return import.meta.env['APP_VERSION'];
}
const store = {
    version: 1,
    setItem(key: string, value: string) {
        ipcRenderer.sendSync('electron-store-set', key, value)
    },
    getItem(key: string) {
        return ipcRenderer.sendSync('electron-store-get', key)
    },
    removeItem(key: string) {
        ipcRenderer.sendSync('electron-store-remove', key)
    },
    clear() {
        ipcRenderer.sendSync('electron-store-clear')
    },
};


const cache = {

    get(key: string) {
        const value = store.getItem(key) as string || '';
        try {
            const model = JSON.parse(value);
            return model.value;
        } catch (e) {
            return '';
        }
    },

    set(key: string, val: any, expire: number = 0) {
        const model = JSON.stringify({
            value: val,
            expire: expire > 0 ? Date.now() + expire : expire
        });
        store.setItem(key, model);
        return this;
    }

}

const restrt = () => {
    ipcRenderer.sendSync('__restart__');
}






export default { readFileSync, publish, rsaDecrypt, rsaEncrypt, sign, getDeviceId, getAppVersion, shell, cache, restrt };
